package com.baizhi.zxt.service;

import com.baizhi.zxt.dao.AdminDao;
import com.baizhi.zxt.entity.Admin;
import com.baizhi.zxt.util.ImageCodeUtil;
import com.baizhi.zxt.util.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class AdminServiceImpl implements AdminService{

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void register(Admin admin) {
        String password = admin.getPassword();
        //调用工具类，获取随机盐
        String salt = Md5Utils.getSalt(6);
        //对原始密码加随机盐
        String saltPwd = salt+password+salt;
        //调用工具类，对随机盐后的密码进行md5加密
        String md5Code = Md5Utils.getMd5Code(saltPwd);
        //对传递过来的管理员数据进行加工
        admin.setPassword(md5Code);
        admin.setSalt(salt);
        //调用dao层方法
        adminDao.insert(admin);
    }

    public Map<String, String> getImageCodes() {
        Map<String,String> map = new HashMap<String,String>();
        try {
            //调用工具类获取随机验证码字符
            String code = ImageCodeUtil.getSecurityCode();
            //调用工具类根据随机码生成图片base64形式
            String imgBase64 = ImageCodeUtil.careateImgBase64(code);
            //把base64图片信息存入map
            map.put("imgCode", imgBase64);
            //获取UUID
            String uuid = UUID.randomUUID().toString();
            //把UUID存入map
            map.put("token", uuid);
            //往redis中存验证码
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            ValueOperations valuesOps = redisTemplate.opsForValue();
            valuesOps.set("CODE_" + uuid, code, 1, TimeUnit.MINUTES);
        }catch(Exception e){
            e.printStackTrace();
        }
        return map;
    }

    //登录检查
    public Map<String,String> login(@RequestBody Admin admin,String token){
        Map<String,String> map = new HashMap<String,String>();
        //从redis中获取服务器上的验证码
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations valueOps = redisTemplate.opsForValue();
        Object obj = valueOps.get("CODE_"+token);
        //检查验证码
        if(obj == null){
            map.put("message","验证码过期！！！");
            map.put("state","error");
            return map;
        }

        String serverCode = obj.toString();
        if(!admin.getEnCode().equals(serverCode)){
            map.put("message","验证码错误！！！");
            map.put("state","error");
            return map;
        }

        //验证码正确,检查帐号密码
        Admin admin1=adminDao.selectByUsername(admin.getUsername());
        if(admin1 == null){
            map.put("message", "用户不存在！！！");
            map.put("state", "error");
            return map;
        }else{ //帐号存在
            if (admin1.getStatus()=="0"){//如果用户状态是0冻结
                map.put("message", "用户已被冻结！！！");
                map.put("state", "error");
                return map;
            }
            //获取输入的密码
            String password = admin.getPassword();
            //加DB相同的盐
            String md5Pwd = admin1.getSalt() + password + admin1.getSalt();
            //对加盐后的密码md5 md5Pwd
            String md5Code = Md5Utils.getMd5Code(md5Pwd);
            if (md5Code.equals(admin1.getPassword())){ //ok
                map.put("state", "success");
                map.put("message", token);
                valueOps.set("TOKEN_"+token, admin1);
            }else{
                map.put("state", "error");
                map.put("message", token);
                return map;
            }
        }
        return map;
    }

   //获取登录用户信息
    public Admin getUserInfo(String token){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations valueOps = redisTemplate.opsForValue();
        return (Admin) valueOps.get("TOKEN_"+token);
    }



    //退出
    public void logout(String token){
        //从redis中删除登录
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.delete("TOKEN_"+token);
    }
   @Override
   @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
   public Admin queryByUsername(String username) {
       Admin admin = adminDao.selectByUsername(username);
       return admin;
   }
}
